"""
File: sfo_67_convert_string_to_int_s1.py
Created Time: 2021-12-09
Author: Krahets (krahets@163.com)
"""

from include import *


# ===== Solution Code =====
class Solution:
    def strToInt(self, str: str) -> int:
        str = str.strip()  # 删除首尾空格
        if not str:
            return 0  # 字符串为空则直接返回
        res, i, sign = 0, 1, 1
        int_max, int_min, bndry = 2**31 - 1, -(2**31), 2**31 // 10
        if str[0] == "-":
            sign = -1  # 保存负号
        elif str[0] != "+":
            i = 0  # 若无符号位，则需从 i = 0 开始数字拼接
        for c in str[i:]:
            if not "0" <= c <= "9":
                break  # 遇到非数字的字符则跳出
            if res > bndry or res == bndry and c > "7":
                return int_max if sign == 1 else int_min  # 数字越界处理
            res = 10 * res + ord(c) - ord("0")  # 数字拼接
        return sign * res


# ======= Test Case =======
str = "42"
# ====== Driver Code ======
slt = Solution()
res = slt.strToInt(str)
print(res)
